import WebSocket from "ws";
import { exec } from "child_process";
import iconv from "iconv-lite";
import { SocketTypeEnum, mainType } from "./socketTypeEnum.js";
// import { initWebSocket, sendWebSocket } from "./websocket/websocket.js";
import { FileBox } from "file-box";
// import { FileBox } from "@juzi/wechaty-puppet/dist/esm/src/config.js";
// console.log("SocketTypeEnum", SocketTypeEnum);

// const encoding = "cp936";
// const binaryEncoding = "binary";
let websocket = null; // 用于存储实例化后websocket
let rec; // 断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let heartBeatInterval = null;
const heartBeatMessage = "heartBeat";
const heartBeatIntervalTime = 30000; // 30 秒发送一次心跳
const reConnectIntervalTime = 5000; // 10 秒发送一次重新连接
var isConnected = false;
var bot; //机器人实例
class ChilldPressDecode {
  encoding = "cp936";
  binaryEncoding = "binary";
  ws = null;
  constructor(ws) {
    this.ws = ws;
  }
  decodeOutput(buffer, encoding) {
    return iconv.decode(buffer, encoding);
  }
  executeAndDecode(command, ws = this.ws) {
    const child = exec(command, { encoding: this.binaryEncoding });
    child.stdout.on("data", (stdout) => {
      const decodedStdout = this.decodeOutput(
        Buffer.from(stdout, this.binaryEncoding),
        this.encoding
      );
      // ws.send({ type: "exec", content: decodedStdout }); // 将输出发送到客户端
    });
    child.stderr.on("data", (stderr) => {
      const decodedStderr = decodeOutput(
        Buffer.from(stderr, this.binaryEncoding),
        this.encoding
      );
      // ws.send({ type: "exec", content: `Error: ${decodedStderr}` }); // 发送错误信息
    });
  }
}
// 创建websocket
function creatWebSocket(wsUrl) {
  console.log("websocket==================");
  try {
    initWebSocket(wsUrl); // 初始化websocket连接
  } catch (e) {
    console.log("尝试创建连接失败");
    reConnect(wsUrl); // 如果无法连接上 webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
  }
}

// 初始化websocket
function initWebSocket(wsUrl, Bot) {
  console.log(123);
  if (!bot) {
    bot = Bot;
  }
  console.log("初始化ws");
  websocket = new WebSocket(wsUrl);
  // console.log("websocket:", websocket);
  websocket.onopen = function () {
    websocketOpen();
  };
  // 接收
  websocket.onmessage = function (e) {
    websocketonmessage(e);
  };
  // 连接发生错误
  websocket.onerror = function () {
    console.log("WebSocket连接发生错误");
    //     isConnect = false; // 连接断开修改标识
    reConnect(wsUrl); // 连接错误 需要重连
  };
  websocket.onclose = function (e) {
    console.log("WebSocket连接断开");
    websocketclose(e);
    // 添加重新连接逻辑
    reConnect(websocket.url || "");
  };
}

// 定义重连函数
const reConnect = (wsUrl) => {
  console.log("尝试重新连接");
  if (isConnected) return; // 如果已经连上就不在重连了
  rec && clearTimeout(rec);
  rec = setTimeout(function () {
    clearHeartbeat();
    // 延迟5秒重连  避免过多次过频繁请求重连
    creatWebSocket(wsUrl);
  }, reConnectIntervalTime);
};
function sendHeartbeat() {
  if (websocket && isConnected) {
    const sendMsg = JSON.stringify({
      Type: SocketTypeEnum.HeartBeat,
      Data: heartBeatMessage,
    });
    console.log("心跳发送的数据: ", sendMsg);
    websocket.heartBeat = 1;
    websocket.send(sendMsg);
    setTimeout(() => {
      if (websocket.heartBeat == 1) {
        websocket.onclose();
      }
    }, 2000);
  }
}

// 创建连接
function websocketOpen() {
  console.log("连接成功");
  // store.dispatch("websocket/connect"); // 修改连接状态
  isConnected = true;
  startHeartbeat();
}

function startHeartbeat() {
  console.log("开启ws心跳");
  heartBeatInterval = setInterval(sendHeartbeat, heartBeatIntervalTime);
}

function clearHeartbeat() {
  if (heartBeatInterval) {
    clearInterval(heartBeatInterval);
    heartBeatInterval = null;
  }
}

async function startBot() {
  console.log("准备重新启动!!");
  sendWebSocket({ Type: SocketTypeEnum.Console, Data: "准备重新启动!!" });
  await bot.start();
  console.log("重新启动完成!!!");
  sendWebSocket({ Type: SocketTypeEnum.Console, Data: "重新启动完成!!!" });
}

async function logoutBot() {
  // 根据当前机器人登录/注销的状态做某些事情
  if (bot.isLoggedIn) {
    await bot.logout();
  } else {
    sendWebSocket({ Type: SocketTypeEnum.Console, Data: "Bot not logined" });
    console.log("Bot not logined");
  }
}

async function stopBot() {
  await bot.stop();
}
// eventBus.on("wsMseeage", () => {
//   console.log("内部自己触发");
// });
// 数据接收
async function websocketonmessage(e) {
  // console.log(e.data);
  console.log(
    "监听到ws的相关信息-------------------------------------------------"
  );
  const data = JSON.parse(e.data);
  // eventBus.emit("wsMseeage", data);
  console.log("接受到的对话data", data);

  switch (data.Type) {
    case SocketTypeEnum.HeartBeat:
      websocket.heartBeat = 0;
      break;
    case SocketTypeEnum.Console:
      if (data.Data === "stop") {
        // stopBot();
        bot.stop();
      } else if (data.Data === "reset") {
        startBot();
      }
      break;
    case SocketTypeEnum.AnswerMsg:
      console.log(data);
      const AnswerData = JSON.parse(data.Data);
      console.log("AnswerData", AnswerData);

      const room = await bot.Room.find({ topic: AnswerData.GroupName });
      // console.log("room信息:", room);
      /**回复回传数据 */
      const ReplyMsg = (row, id, url = "") => {
        if (row.payload.type == 7) {
          sendWebSocket({
            Type: SocketTypeEnum.replyMsg,
            Data: JSON.stringify({
              Id: id,
              ContentId: row.id,
              ContentPath: "",
            }),
          });
        } else if (row.payload.type == 6) {
          sendWebSocket({
            Type: SocketTypeEnum.replyMsg,
            Data: JSON.stringify({
              Id: id,
              ContentId: row.id,
              ContentPath: url,
            }),
          });
        }
      };
      if (room) {
        const members = await room.memberAll();
        // console.log("members", members);
        // console.log("类型", AnswerData.ContentType);
        const targetContact = members.find(
          (member) => member.payload.name === AnswerData.SendUserName
        );
        if (mainType.text == AnswerData.ContentType) {
          let text =
            AnswerData.QuestionContentType == 0
              ? AnswerData.FullAnswer
              : AnswerData.Answer;
          await room
            .say(`${text}`, targetContact)
            .then((result) => {
              console.log("发送成功", result);
              ReplyMsg(result, AnswerData.Id);
            })
            .catch((err) => {});
        } else if (mainType.image == AnswerData.ContentType) {
          // console.log(
          //   "图片",
          //   AnswerData.FullAnswer.split("======")[1],
          //   AnswerData.FullAnswer.substring(
          //     AnswerData.FullAnswer.lastIndexOf("/") + 1,
          //     AnswerData.FullAnswer.length
          //   )
          // );
          // await room.say(targetContact);
          // await room.say(
          //   FileBox.fromUrl(
          //     "https://huan.github.io/file-box/images/file-box-logo.jpg",
          //     "logo.jpg"
          //   )
          // );
          console.log(
            "图片名称:",
            AnswerData.Answer.substring(
              AnswerData.FullAnswer.lastIndexOf("/") + 1,
              AnswerData.FullAnswer.length
            )
          );
          await room
            .say(
              FileBox.fromUrl(
                AnswerData.Answer,
                AnswerData.Answer.substring(
                  AnswerData.FullAnswer.lastIndexOf("/") + 1,
                  AnswerData.FullAnswer.length
                )
              )
            )
            .then(async (result) => {
              console.log("发送成功");
              ReplyMsg(
                result,
                AnswerData.Id,
                (await result.toFileBox()).remoteUrl
              );
            })
            .catch((err) => {
              console.log(err);
            });
        }
        // console.log("targetContact.name", targetContact);
        // console.log("准备开始发送信息: " + AnswerData.FullAnswer); // if (targetContact) {

        // await room.say(`${AnswerData.FullAnswer}`, targetContact);
        // await room.say(
        //   FileBox.fromUrl(
        //     "https://huan.github.io/file-box/images/file-box-logo.jpg",
        //     "logo.jpg"
        //   )
        // );
        // } else { //   console.log( //     `Contact with nickname ${contactNicknameToMention} not found in the room.` //   ); // }
      }
      break;
  }
  // console.log("数据接收", e.data);
}

// 关闭
function websocketclose(e) {
  // console.log(e);
  // store.dispatch("websocket/disconnect"); // 修改连接状态
  isConnected = false;
  // console.log("connection closed (" + e.code + ")");
  clearHeartbeat();
}
// 数据发送
function websocketsend(data) {
  console.log("发送的数据", JSON.stringify(data));
  if (websocket && isConnected) {
    console.log("准备发送前的回调!!");
    // 检查连接状态
    websocket.send(JSON.stringify(data));
  } else {
    // ElMessage({
    //   showClose: true,
    //   message: "请选择设备连接",
    //   type: "error",
    // });
  }
}

// 发送
function sendWebSocket(data) {
  // 如果未保持连接状态 不允许直接发送消息 提示请选择连接设备
  if (!isConnected) {
    // ElMessage({
    //   showClose: true,
    //   message: "请选择设备连接",
    //   type: "error",
    // });
  } else {
    websocketsend(data);
    console.log("------------------");
  }
}

// 关闭
const closeWebSocket = () => {
  if (websocket) {
    websocket.close();
    // ElMessage({
    //   showClose: true,
    //   message: "设备已关闭",
    //   type: "success",
    // });
  }
};

export { initWebSocket, sendWebSocket, creatWebSocket, closeWebSocket };
